const { app, BrowserWindow, ipcMain,clipboard } = require('electron');
const path = require('path');
const fs = require('fs');

let mainWindow;

function createWindow() {
    mainWindow = new BrowserWindow({
        width: 1200,
        height: 800,
        webPreferences: {
            nodeIntegration: false,
            contextIsolation: true,
            preload: path.join(__dirname, 'preload.js')
        }
    });

    mainWindow.loadFile('index.html');

    // 开发时打开开发者工具
    // mainWindow.webContents.openDevTools();
}

// 文件操作API
ipcMain.handle('read-file', async () => {
    try {
        const dataPath = path.join(app.getPath('userData'), 'project_data.json');
        if (fs.existsSync(dataPath)) {
            const data = fs.readFileSync(dataPath, 'utf8');
            return JSON.parse(data);
        }
        return [];
    } catch (error) {
        console.error('读取文件失败:', error);
        return [];
    }
});

ipcMain.handle('write-file', async (event, data) => {
    try {
        const dataPath = path.join(app.getPath('userData'), 'project_data.json');
        fs.writeFileSync(dataPath, JSON.stringify(data, null, 2), 'utf8');
        return { success: true };
    } catch (error) {
        console.error('写入文件失败:', error);
        return { success: false, error: error.message };
    }
});

ipcMain.handle('copy-path-to-clipboard', async (event, path) => {
    clipboard.writeText(path);
    return true;
});

app.whenReady().then(createWindow);

app.on('window-all-closed', () => {
    if (process.platform !== 'darwin') {
        app.quit();
    }
});
ipcMain.handle('get-data-path', async () => {
    return path.join(app.getPath('userData'), 'project_data.json');
});

app.on('activate', () => {
    if (BrowserWindow.getAllWindows().length === 0) {
        createWindow();
    }
});